//
//  JokesMainViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "JokesMainViewController.h"
#import "Path.h"
#import "Mybutton.h"
#import "MyLayoutOfJokes.h"
#import "JokesCollectionViewCell.h"
#import "JokesModel.h"
#import "AsyncGETParser.h"
#import "FileNameList.h"
#import "MJRefresh.h"



NSInteger count = 0;

@interface JokesMainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

{
    // 为了控制头像
    NSInteger _index;
    NSInteger _first;
    
}

@property (nonatomic, retain) UICollectionView *collection;

@property (nonatomic,retain) UIImageView *backImage;

@property (nonatomic, retain) UIVisualEffectView *effectview;

// 装数据
@property (nonatomic, retain) NSMutableArray *arrayOfdata;

@property (nonatomic, retain) Mybutton *personButton;

// 用于刷新数据
@property (nonatomic, retain) NSMutableDictionary *info;

@property (nonatomic, retain) UIView *backView;


@end

@implementation JokesMainViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfdata = [NSMutableArray array];
        self.info = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)dealloc
{
    [_backView release];
    [_personButton release];
    [_backImage release];
    [_effectview release];
    [_collection release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"乐";
    [self handelData];
}

- (void)refresh
{
    // 下拉加载
    count++;
    NSString *num = [NSString stringWithFormat:@"%ld", count];
    self.collection.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        NSDictionary *dic = @{@"page" : num};
        [AsyncGETParser asyncGETParserWithURLString:LY_Jokes fileName:FILE_Jokes pamarters:dic block:^(NSData *data) {

            // 重新解析
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic objectForKey:@"list"];
            // 间数据添加到数组中
            for (int i = 0; i < array.count; i++) {
                JokesModel *model = [[JokesModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
                [model release];
            }
            
            if (self.arrayOfdata.count > 0) {
                [self.collection reloadData];
            }
            
        }];
        [self.collection.footer endRefreshing];
    }];
    self.collection.footer.hidden = YES;
}

// 数据处理
- (void)handelData
{
    NSDictionary *dic = @{@"page" : @"1"};
   [AsyncGETParser asyncGETParserWithURLString:LY_Jokes fileName:FILE_Jokes pamarters:dic  block:^(NSData *data) {
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       NSArray *array = [dic objectForKey:@"list"];
       self.info = [dic objectForKey:@"info"];
       
       for (int i = 0; i < array.count; i++) {
           
           JokesModel *model = [[JokesModel alloc] init];
           [model setValuesForKeysWithDictionary:array[i]];
           [self.arrayOfdata addObject:model];
           [model release];
       }
       if (self.arrayOfdata.count > 0) {
           //[self.collection reloadData];
           [self createSubView];
           
       }
       
   }];
}

- (void)createSubView
{
    MyLayoutOfJokes *layout = [[MyLayoutOfJokes alloc] init];
    layout.dataArray = self.arrayOfdata;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 240 * heightFit, self.view.frame.size.width, 300 * heightFit) collectionViewLayout:layout];
    self.collection.delegate = self;
    
    self.collection.backgroundColor = [UIColor clearColor];
    self.collection.showsHorizontalScrollIndicator = NO;
    self.collection.pagingEnabled = YES;
    self.collection.dataSource = self;
    
    // 注册
    [self.collection registerClass:[JokesCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.backView addSubview:self.collection];
    [_collection release];
}

#pragma mark - collectionView的协议方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrayOfdata.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JokesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath ];
    if (indexPath.item == 0 && _first != 1 && self.arrayOfdata.count > 0) {
        JokesModel *model = self.arrayOfdata[indexPath.item];
        self.personButton.model = model;
    }
    JokesModel *model = self.arrayOfdata[indexPath.item];
    cell.model = model;
    return cell;
}

#pragma UIScrollViewDelegate方法

// 进行加载数据
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _first = 1;
     // 为头像赋值
    
    _index = scrollView.contentOffset.x /  self.view.frame.size.width;
    // 防止数组越界
    if (self.arrayOfdata.count > 0) {
        JokesModel *model = self.arrayOfdata[_index];
        self.personButton.model = model;
    }
    
    if (scrollView.contentOffset.x == (self.arrayOfdata.count - 1) * self.view.frame.size.width && [self.info objectForKey:@"maxid"] != nil) {
        
        // 进行网络加载
        
        NSDictionary *dic = @{@"page" : @"1", @"maxid" : [self.info objectForKey:@"maxid"]};
        [self.info removeAllObjects];
        [AsyncGETParser asyncGETParserWithURLString:LY_RefreshJokes fileName:FILE_Jokes pamarters:dic block:^(NSData *data) {
            
            // 重新解析, 加载数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic objectForKey:@"list"];
            self.info = [dic objectForKey:@"info"];
            // 间数据添加到数组中
            for (int i = 0; i < array.count; i++) {
                JokesModel *model = [[JokesModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
                [model release];
            }
            if (self.arrayOfdata.count > 0) {
                [self.collection reloadData];
            }
        }];
    }
}

// 设置背景图片
- (void)receiveBackImageName:(NSString *)imageName
{
#if 0
    self.backImage = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
    self.backImage.userInteractionEnabled = YES;
    [self.view addSubview:self.backImage];
    self.backImage.image = [UIImage imageWithContentsOfFile:[Path pathOfImageWithName:imageName]];
    
    // 铺毛玻璃
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
    self.effectview.frame = [[UIScreen mainScreen] bounds];
    [self.backImage addSubview:self.effectview];
    
    self.personButton = [[Mybutton alloc] initWithFrame:CGRectMake(10, 144, self.view.frame.size.width - 20, 80)];
    [self.effectview.contentView addSubview:self.personButton];
    
    [_personButton release];
    [_effectview release];
    [_backImage release];
#endif
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.backView];
    [_backView release];

    self.personButton = [[Mybutton alloc] initWithFrame:CGRectMake(10 * widthFit, 144 * heightFit, (self.view.frame.size.width - 20) * widthFit, 80 * heightFit)];
    [self.backView addSubview:self.personButton];
    [_personButton release];
    [self createSubView];
    //[self refresh];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
